import requests
import base64
from PIL import Image
import io

def encode_image_to_base64(image_path):
    """将图片转换为base64编码"""
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')

def query_llava_model(image_path, prompt):
    """使用Llava模型进行多模态推理"""
    # Ollama API endpoint
    url = "http://localhost:11434/api/generate"
    
    # 准备请求数据
    data = {
        "model": "llava",
        "prompt": prompt,
        "images": [encode_image_to_base64(image_path)],
        "stream": False
    }
    
    # 发送请求
    response = requests.post(url, json=data)
    
    if response.status_code == 200:
        return response.json()["response"]
    else:
        return f"Error: {response.status_code}"

def main():
    # 示例使用
    image_path = "test_image.jpg"  # 替换为你的图片路径
    prompt = "请描述这张图片中的内容"
    
    try:
        result = query_llava_model(image_path, prompt)
        print("模型响应:", result)
    except Exception as e:
        print(f"发生错误: {str(e)}")

if __name__ == "__main__":
    main() 